package com.rangers.manage.email.strategy;

import java.io.StringWriter;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.springframework.util.Assert;

import com.rangers.manage.email.domain.EmailDto;

public class VelocityStrategy implements EmailStrategy {

	private VelocityEngine velocityEngine;

	private VelocityContext velocityContext;

	/**
	 * 相对路径名:velocity/velocityTemplate.vm
	 */
	private String templateName;

	public VelocityStrategy setVelocityEngine(VelocityEngine velocityEngine) {
		this.velocityEngine = velocityEngine;
		return this;
	}

	/**
	 * 创建策略
	 * 
	 * @param velocityContext
	 *            <li>如:new VelocityContext().put("name", "Jack");</li>
	 * @param templateName
	 *            <li>相对路径名:velocity/velocityTemplate.vm</li>
	 */
	public VelocityStrategy(VelocityContext velocityContext, String templateName) {
		this.velocityContext = velocityContext;
		this.templateName = templateName;
	}

	@Override
	public String getMsgContent(EmailDto vo) {
		Assert.notNull(this.velocityEngine, "velocityEngine cannot be null -> velocity模板引擎没有配置");
		Template template = this.velocityEngine.getTemplate(this.templateName, "UTF-8");
		StringWriter sw = new StringWriter();
		template.merge(velocityContext, sw);
		return sw.toString();
	}
}
